package com.ruoyi.project.pay;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.utils.Md5Utils;
import com.ruoyi.common.utils.ServletUtils;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.project.channel.businessInfo.domain.BusinessInfo;
import com.ruoyi.project.channel.businessInfo.service.IBusinessInfoService;
import com.ruoyi.project.channel.businessRate.service.IBusinessRateService;
import com.ruoyi.project.channel.channelAccount.service.IChannelAccountService;
import com.ruoyi.project.channel.channelCode.service.IChannelCodeService;
import com.ruoyi.project.channel.channelOrder.domain.ChannelOrder;
import com.ruoyi.project.channel.channelOrder.service.IChannelOrderService;
import com.ruoyi.project.channel.clientInfo.domain.ClientInfo;
import com.ruoyi.project.channel.goodsInfo.domain.GoodsInfo;
import com.ruoyi.project.channel.goodsInfo.service.IGoodsInfoService;
import com.ruoyi.project.channel.payerBusinessInfo.domain.PayerBusinessInfo;
import com.ruoyi.project.channel.payerBusinessInfo.service.IPayerBusinessInfoService;
import com.ruoyi.project.channel.salesmanInfo.service.ISalesmanInfoService;
import com.ruoyi.project.channel.salesmanScore.domain.SalesmanScore;
import com.ruoyi.project.channel.salesmanScore.mapper.SalesmanScoreMapper;
import com.ruoyi.project.channel.salesmanScore.service.ISalesmanScoreService;
import com.ruoyi.project.monitor.operlog.service.IOperLogService;
import com.ruoyi.project.pay.domain.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.*;

/**
 * swagger 测试方法
 *
 * @author ruoyi
 */
@Api("支付管理")
@Controller
@RequestMapping("/pay/*")
public class PayController extends BaseController {
    @Autowired
    private PayServiceImpl payService;
    @Autowired
    private IChannelOrderService channelOrderService;
    @Autowired
    private IChannelAccountService channelAccountService;
    //    private String privateKey = "MIIEvwIBADANBgkqhkiG9w0BAQEFAASCBKkwggSlAgEAAoIBAQDL+EzOYUxX7iOvof3KuGPHGA8EfYzFv2q7VEQgEsIGbQk1OHwFn+14tdq3X42iPjcTHCiYdImemG8+xGr0Qk4EZq2UB3wt3A6K1c0eCNQUSvDPCGH81nQ4lASmNYCMfaYAkCOVQCe5EgpM1PaptMm6q4aOB+nQK6K6uboP+muvTp6TjeLieVOX3aUTOE6hbQKeEAtD4jqHsCORBqAMyADq1/Kp1pIzeFe0OFssjGO61Kj2gykHB5cc+tWgax60ill9iXTLWzEifGiQQUB1Ru0zBTrSGY80hc0fhUa61jiqnZnlneZDcScFAdFs4GvOH977lcL2IVx5xse9Ml5kQBqlAgMBAAECggEAPj7oMZM/2RWzjkXBTbw3tuqAqr4l17MyvzhYEfGnhI6B4Nv7/TtxHQViWdOvRXP3Gr3dJalq1htu15jZivExHea30hT2sIgXaAcXMbNABXFZS9UjEiXgEeQaBx8Mu9Mcdc+HDGUnujLnMctL+z5Q0cbGqVGA6SZn4tQLFBU4B6dLAlVJ5OAHUT3wB6x168xoKAOkUprYE3YIbE/t6Zl4lw/REihde1xPA39Df+v54FU0DKwMLwHFMrqTR9jnwA+q8FBIRsCEG9zgQ0mq+DEdjv70gjFGaTZYrv9ytSwoA0s9QtZBVPioO30IWTXJ+S+I96T2VNq9Wkx0JginjgAUAQKBgQDnTotmLJefiXRNlRllhrJwukOWww3zkE8MpViOVrzmX3ZDQ24UAHPTyp70ph24oQNe2O05M/QqOeMDTfwQgQ6tlRNh6mExAFmdTSkhLEgVK+v51xet3FxzORhGy1qu1eo2dKS+bAkeorZFNowtiPmDSnk4XXbiXc4Tp6YuwQOFuQKBgQDhvqg3+O3V1QAO6/A/ODCwWTPtDOxOkMx1GT5Sgr+1kjy3kRcxJZSPyxsndQfwKmsJyMwYcC8E/vLhcjoEdfK5bNK8+kJcVvYyeqw3BKR0FXqxmxZACFS+l+Ifns5QSgJvI7f50pFwKhzN34SJCQWQB1vZunG4GWNsk77NdAjyTQKBgQCZJQDYmkedQkW1pDUXajI0vq5HYEeZbn9YERVr0HPrV2MWr8tvBMmrfSj3NBDTkA+KObf+uq47Uu5B3t04FCqitOQLXUISTngG1PKZWxcypUzsswOjghXX2AKBxNv6i/kxKtN0nFUBapuhgbcX4uvIiINv1ToEMDVkAAjgRbzOSQKBgQDJq740Ytp20Zb/vaAfml9E7CwLdiQV/B3r7uVSaSRDXaWIiMIjUeNqopRbp52z3PFLCGvs2SvoVqs85QMXwRdat/F8ikaGn9nKNvVrIWaZnibCTD6QbeDndGC6xvChobyS9WICeS8c+UJKWYjZs4mYpjpURNAbG/NKqKMogKUNcQKBgQCMmlaD/0wywC5rKNbSAVA0rbYS4pWvukso9LixfNnWS5XudCM4fFbSmQeuremQfJ5FxxyRlTVMHl9G8KnC4QoxTkE2urptpQLz0z/rjpPnVGHnNpROcP4gv602+7HXwW1ww45GXX4zGwXdOxfSl5kXiWr+0cnX8ygZeIs0zDVGxA==";
//    private String publicKey = "MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAmOji8TA47cwgyr3sFjY7ZRrjJufyZSCluD5TFP1n2cADFl2mgPoYWjklDBWZ36Adu0QjHxVBGCoZt9Z2Pb/bwO2Cigi3Z+3IELJtpcPUSaiyGFGKwDjf5WmDIPeewr5vjrjkj/v8I3WF1Ny6jb/vO4PNmjKqGzplMANp+qM48m6AgJmEH5Nhv3go6WuertzDjH6bp4ko/i5W9HwjpK2MjQjq/LP0KaFs+lFSCo9eqOK7tnhMwiXwW/OG4HTUl93HdtlrxhMmsf6x5DOlxyRaUi+ayyIm/d2LNxowJEZHK4VRs+Y2YcG40bleSNV83tTenI82PvcNcBwatD1jal6DzQIDAQAB";
    @Autowired
    private PayConfig payConfig;
    @Autowired
    private IChannelCodeService channelCodeService;
    private static final Logger log = LoggerFactory.getLogger(PayController.class);
    @Autowired
    private IPayerBusinessInfoService payerBusinessInfoService;
    @Autowired
    private IBusinessInfoService businessInfoService;
    @Autowired
    private IOperLogService operLogService;
    @Autowired
    private IBusinessRateService businessRateService;
    @Autowired
    private ISalesmanScoreService salesmanScoreService;
    @Autowired
    private SalesmanScoreMapper salesmanScoreMapper;
    @Autowired
    private IGoodsInfoService goodsInfoService;

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param channelOrder
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("order")
    @ResponseBody
    public AjaxResult addOrder(@RequestBody ChannelOrder channelOrder) {
        // 第三方创建订单接口
        // 获取商户信息
        // md5秘钥校验
        log.info("下单客户端ip：" + ServletUtils.getRequest().getRemoteHost() + ";" + channelOrder.toString());
        return payService.addOrder(channelOrder, null);
    }

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param channelOrder
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("order/view")
    public String orderView(ChannelOrder channelOrder, ModelMap mmap) {
        log.info("orderView下单客户端ip：" + ServletUtils.getRequest().getRemoteHost() + ";" + channelOrder.toString());
        AjaxResult result = payService.addOrder(channelOrder, null);
        if (result.get("data") == null) {
            mmap.put("qrcode", result.get("msg"));
            return "openOutTime";
        }

        long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
        mmap.put("time", time);
        if (time <= 0) {
            mmap.put("qrcode", "订单已超时");
            return "openOutTime";
        }
        if (channelOrder.getPayType().equals("23")) {
            // 微博红包
            mmap.put("str", channelOrder.getPayUrl());
            return "openWB";
        }
        mmap.put("qrcodeUrl", channelOrder.getCardId());
        return "openZYJS";
    }

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param channelOrder
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("order/formView")
    public String orderFormView(ChannelOrder channelOrder, ModelMap mmap, HttpServletRequest request) {
        log.info("orderFormView下单客户端ip：" + ServletUtils.getRequest().getRemoteHost() + ";" + channelOrder.toString());
        String agent = request.getHeader("user-agent");
        boolean isPc = true;
        if (agent.toLowerCase().contains("android") || agent.toLowerCase().contains("webos") || agent.toLowerCase().contains("iphone") || agent.toLowerCase().contains("blackberry")) {
            isPc = false;
        }
        channelOrder.setServerType("2");
        AjaxResult result = payService.addOrder(channelOrder, null);

        if (result.get("data") == null) {
            mmap.put("qrcode", result.get("msg"));
            return "openOutTime";
        }

        JSONObject r = (JSONObject) result.get("data");
        if (r.getString("third") != null && r.getString("third").equals("true")) {
            mmap.put("payUrl", r.getString("payUrl"));
            return "SH";
        }

        long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
        mmap.put("time", time);
        if (time <= 0) {
            mmap.put("qrcode", "订单已超时");
            return "openOutTime";
        }

        if (channelOrder.getPayType().equals("23")) {
            // 微博红包
            mmap.put("str", channelOrder.getPayUrl());
            return "openWB";
        } else if (channelOrder.getPayType().equals("09") || channelOrder.getPayType().equals("31")) {
            // 支付宝固码
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openGM";
        } else if (channelOrder.getPayType().equals("25")) {
            // 支付宝企业码
            return "openOneGM";
        } else if (channelOrder.getPayType().equals("26")) {
            // 转账
            return "openAlipayZZ";
        } else if (channelOrder.getPayType().equals("27")) {
            // 智享
            return "openZhiXiang";
        } else if (channelOrder.getPayType().equals("30")) {
            mmap.put("channelOrder", channelOrder);
            return "openUX";
        } else if (channelOrder.getPayType().equals("28") && isPc) {
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", url);
            mmap.put("clipUrl", url);
            return "openPcAlipay";
        } else if (channelOrder.getPayType().equals("28") && isPc == false) {
            time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcode", channelOrder.getPayUrl());
            return "openTBHB";
        } else if (channelOrder.getPayType().equals("29") && isPc) {
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", url);
            mmap.put("clipUrl", url);
            return "openPcAlipay";
        } else if (channelOrder.getPayType().equals("29") && isPc == false) {
            time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcode", channelOrder.getCardId());
            return "openTBHB";
        }

        mmap.put("qrcodeUrl", channelOrder.getCardId());
        return "openZYJS";
    }

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param formOrder
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("order/form")
    @ResponseBody
    public AjaxResult addFormOrder(ChannelOrder formOrder) {
        // 第三方创建订单接口
        // 获取商户信息
        // md5秘钥校验
        log.info("addFormOrder下单客户端ip：" + ServletUtils.getRequest().getRemoteHost() + ";" + formOrder.toString());
        formOrder.setServerType("2");
        return payService.addOrder(formOrder, null);
    }

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param formOrder
     * @return
     */
    @ApiOperation("创建订单")
    @PostMapping("apisubmit")
    public String apisubmit(TempOrder formOrder, ModelMap mmap) {
        // 第三方创建订单接口
        // 获取商户信息
        // md5秘钥校验
        ChannelOrder channelOrder = new ChannelOrder();
        channelOrder.setServerType("3");
        channelOrder.setBusinessId(formOrder.getCustomerid());
        channelOrder.setChildOrderno(formOrder.getSdorderno());
        channelOrder.setAmount(formOrder.getTotal_fee());
        channelOrder.setPayType(formOrder.getPaytype());
        channelOrder.setBankMark(formOrder.getBankcode());
        channelOrder.setServerUrl(formOrder.getNotifyurl());
        channelOrder.setReturnUrl(formOrder.getReturnurl());
        channelOrder.setRemark(formOrder.getRemark());
        channelOrder.setSign(formOrder.getSign());
        AjaxResult result = payService.addOrder(channelOrder, formOrder);
        if (result.get("data") != null) {
            HashMap<String, String> r = (HashMap<String, String>) result.get("data");
            mmap.put("payUrl", r.get("payUrl"));
        } else {
            mmap.put("result", result.get("msg"));
            mmap.put("payUrl", "error");
        }

        return "SH";
    }

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param formOrder
     * @return
     */
    @ApiOperation("查询订单")
    @PostMapping("apiorderquery")
    public String queryPostOrder(TempOrder formOrder, ModelMap mmap) {
        ChannelOrder channelOrder = new ChannelOrder();
        channelOrder.setServerType("3");
        channelOrder.setBusinessId(formOrder.getCustomerid());
        channelOrder.setChildOrderno(formOrder.getSdorderno());
        channelOrder.setAmount(formOrder.getTotal_fee());
        channelOrder.setPayType(formOrder.getPaytype());
        channelOrder.setBankMark(formOrder.getBankcode());
        channelOrder.setServerUrl(formOrder.getNotifyurl());
        channelOrder.setReturnUrl(formOrder.getReturnurl());
        channelOrder.setRemark(formOrder.getRemark());
        channelOrder.setSign(formOrder.getSign());
        AjaxResult result = payService.addOrder(channelOrder, formOrder);
        if (result.get("data") != null) {
            HashMap<String, String> r = (HashMap<String, String>) result.get("data");
            mmap.put("payUrl", r.get("payUrl"));
        } else {
            mmap.put("result", result.get("msg"));
            mmap.put("payUrl", "error");
        }
        return "SH";
    }

    /**
     * 聚合系统接收上游方创建订单
     *
     * @param formOrder
     * @return
     */
    @ApiOperation("查询订单")
    @GetMapping("apiorderquery")
    @ResponseBody
    public JSONObject queryOrder(TempOrder formOrder) {
        return payService.queryOrder(formOrder);
    }

    /**
     * 用来做测试的
     *
     * @param orderId
     * @param mmap
     * @return
     */
    @ApiOperation("订单付款页面")
    @GetMapping("orderSuccess/{orderId}")
    public String orderSuccess(@PathVariable("orderId") String orderId, ModelMap mmap) {
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        mmap.put("channelOrder", channelOrder);
        mmap.put("qrcode", "订单已成功");
        return "openOutTime";
    }

    /**
     * 用来做测试的
     *
     * @param orderId
     * @param mmap
     * @param clientType pc phone
     * @return
     */
    @ApiOperation("订单付款页面")
    @GetMapping("orderView/{orderId}")
    public String orderView(@PathVariable("orderId") String orderId, ModelMap mmap, HttpServletRequest request, String clientType) {
        log.info("客户ip：" + ServletUtils.getRequest().getRemoteHost() + ";" + orderId);
        String agent = request.getHeader("user-agent");
        boolean isPc = true;
        if (agent.toLowerCase().contains("android") || agent.toLowerCase().contains("webos") || agent.toLowerCase().contains("iphone") || agent.toLowerCase().contains("blackberry")) {
            isPc = false;
        }
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        // 记录用户地址
//        OperLog operLog = new OperLog();
//        operLog.setOperIp(ServletUtils.getRequest().getRemoteHost());
//        operLog.setOperUrl("orderView/{orderId}");
//        operLog.setTitle("订单付款页面");
//        operLog.setErrorMsg(channelOrder.getBusinessName() + ":" + channelOrder.getBusinessId());
//        operLog.setOperLocation(AddressUtils.getRealAddressByIP(operLog.getOperIp()));
//        operLogService.insertOperlog(operLog);
//        log.info("当前操作者地址:" + operLog.getOperLocation());
        // 如果是支付宝固码则对地域进行特殊处理
//        if(channelOrder.getOrderStatus().equals("0") && channelOrder.getPayType().equals("09") && channelOrder.getBusinessId() != 14){
//            String preAccount = channelOrder.getAccount();
//            // 原先的account 是否已经是这个地市 如果是则不需要替换
//            ChannelAccount preSearch = new ChannelAccount();
//            preSearch.setAccount(preAccount);
//            List<ChannelAccount> preAccs =  channelAccountService.selectChannelAccountList(preSearch);
//            if(preAccs.get(0).getAddress()== null || (preAccs.get(0).getAddress()!=null && !preAccs.get(0).getAddress().equals(operLog.getOperLocation()))){
//                BusinessRate searchBR = new BusinessRate();
//                searchBR.setBusinessId(channelOrder.getBusinessId());
//                searchBR.setPayerPayType(channelOrder.getPayType());
//                searchBR.setUseStatus("0");
//                List<BusinessRate> businessRates = businessRateService.selectBusinessRateList(searchBR);
//                ArrayList<Long> ids = new ArrayList<>();
//                for(int m=0;m<businessRates.size();m++){
//                    BusinessRate tmpB = businessRates.get(m);
//                    ids.add(tmpB.getChannelId());
//                }
//                ChannelAccount searchAc = new ChannelAccount();
//                searchAc.setPayType("09");
//                searchAc.setRiskStatus("0");
//                searchAc.setStatus("0");
//                searchAc.setAddress(operLog.getOperLocation());
//                searchAc.getParams().put("cIds",ids);
//                List<ChannelAccount> channelAccounts = channelAccountService.selectChannelAccountList(searchAc);
//                if(channelAccounts.size()>0){
//                    ChannelAccount channelAccount = channelAccounts.get(new Random().nextInt(channelAccounts.size()));
//                    log.info("进入替换操作:"+channelAccount+";原始账号:"+preAccount);
//                    channelOrder.setChannelUserId(channelAccount.getChannelUserId());
//                    channelOrder.setAccount(channelAccount.getAccount());
//                    channelOrder.setCardId(channelAccount.getAppid());
//                    channelOrder.setAccountName(channelAccount.getAlias());
//                    for(int m=0;m<businessRates.size();m++){
//                        BusinessRate tmpB = businessRates.get(m);
//                        if(tmpB.getChannelId().longValue() == channelOrder.getChannelUserId().longValue()){
//                            channelOrder.setBusinessRateId(tmpB.getRateId());
//                            break;
//                        }
//                    }
//                    channelAccount.setRiskStatus("1");
//                    channelAccountService.updateChannelAccount(channelAccount);
//                    // 原先的账号要释放出来
//                    preAccs.get(0).setRiskStatus("0");
//                    channelAccountService.updateChannelAccount(preAccs.get(0));
//                    // 更新订单账号信息
//                    channelOrder.setBankName("匹配城市成功:"+operLog.getOperLocation() );
//                    channelOrderService.updateChannelOrder(channelOrder);
//                    log.info("匹配地市成功:"+operLog.getOperLocation());
//                }
//            }
//        }

        String uri = "";
        mmap.put("channelOrder", channelOrder);
        if (channelOrder.getSuccessTime() != null) {
            mmap.put("qrcode", "订单已成功");
            return "openOutTime";
        } else if (channelOrder.getStatus().equals("1")) {
            mmap.put("qrcode", "订单已超时");
            return "openOutTime";
        } else if (channelOrder.getPayType().equals("06")) {
            // 吱口令
            mmap.put("clipUrl", uri);
            return "openZhikouling";
        } else if (!channelOrder.getPayType().equals("06")) {
            try {
                uri = payConfig.getCaiNiaoHost() + "/pay/alipay?orderId=" + channelOrder.getOrderId();
                mmap.put("qrcode", uri);
                mmap.put("clipUrl", uri);
                if (channelOrder.getPayUrl() != null) {
                    mmap.put("payUrl", URLEncoder.encode(channelOrder.getPayUrl(), "utf-8"));
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        if (channelOrder.getPayType().equals("09") || channelOrder.getPayType().equals("21") || channelOrder.getPayType().equals("31")) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openGM";
        } else if (channelOrder.getPayType().equals("13")) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openZYJS";
        } else if (channelOrder.getPayType().equals("15") || channelOrder.getPayType().equals("16")) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openWXGM";
        } else if (channelOrder.getPayType().equals("17")) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openCloudGM";
        } else if (channelOrder.getPayType().equals("23")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("str", channelOrder.getPayUrl());
            return "openWB";
        } else if (channelOrder.getPayType().equals("18") && !isPc) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openRedPackage";
        } else if (channelOrder.getPayType().equals("18") && isPc) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", url);
            return "openPcAlipayRed";
        } else if (channelOrder.getPayType().equals("19")) {
            // 微信手机号
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openWXSJ";
        } else if (channelOrder.getPayType().equals("10")) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openNXGM";
        } else if (channelOrder.getPayType().equals("12")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openNXYS";
        } else if (channelOrder.getPayType().equals("11")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openClound";
        } else if (channelOrder.getPayType().equals("25")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openOneGM";
        } else if (channelOrder.getPayType().equals("30")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openUX";
        } else if (channelOrder.getPayType().equals("26")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            if (payConfig.getTitle().equals("笨鸟支付")) {
                return "openAlipayZZ2";
            }
            return "openAlipayZZ";
        } else if (channelOrder.getPayType().equals("20")) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openZanBei";
        } else if (channelOrder.getPayType().equals("27")) {
            long time = channelOrder.getCreateTime().getTime() + 600 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openZhiXiang";
        } else if (channelOrder.getPayType().equals("18") && !isPc) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcodeUrl", channelOrder.getCardId());
            return "openRedPackage";
        } else if (channelOrder.getPayType().equals("28") && isPc == false) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", channelOrder.getPayUrl());
            return "openTBHB";
        } else if (channelOrder.getPayType().equals("28") && isPc) {
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", url);
            mmap.put("clipUrl", url);
            return "openPcAlipay";
        } else if (channelOrder.getPayType().equals("29") && isPc) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", url);
            mmap.put("clipUrl", url);
            return "openPcAlipay";
        } else if (channelOrder.getPayType().equals("29") && isPc == false) {
            long time = channelOrder.getCreateTime().getTime() + 240 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            mmap.put("qrcode", channelOrder.getCardId());
            return "openLHQ";
        } else if (channelOrder.getPayType().equals("08") && isPc == true) {
            String url = payConfig.getCaiNiaoHost() + "/pay/orderView/" + channelOrder.getOrderId();
            mmap.put("qrcode", url);
            mmap.put("clipUrl", url);
            return "openPcAlipay";
        } else if (channelOrder.getPayType().equals("04") && isPc == false) {
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            return "openBank";
        } else if ((clientType != null && clientType.equals("pc")) || channelOrder.getPayType().equals("05")) {
            return "openPcAlipay";
        } else if (clientType != null && clientType.equals("phone")) {
            return "openAlipay";
        } else if (isPc == true) {
            return "openPcAlipay";
        } else {
            return "openAlipay";
        }
    }

    /**
     * 下游支付商调用的接口,告诉支付中心 订单已经完成了
     *
     * @param channelOrder
     * @return
     */
    @ApiOperation("更新订单")
    @Log(title = "更新订单", businessType = BusinessType.UPDATE)
    @PostMapping("order/patch")
    @ResponseBody
    public AjaxResult updateOrder(@RequestBody ChannelOrder channelOrder) {
        log.info("回调更新订单,订单id：" + channelOrder.getPtOrderno(), channelOrder);
        // 第三方创建订单接口
        // 获取商户信息
        // md5秘钥校验
        PayerBusinessInfo searchPayInfo = new PayerBusinessInfo();
        searchPayInfo.setBusinessNo(channelOrder.getBusinessId() + "");
        searchPayInfo.getParams().put("payerName", "代理中心");
        List<PayerBusinessInfo> payerInfos = payerBusinessInfoService.selectPayerBusinessInfoList(searchPayInfo);
        if (payerInfos.size() == 0) {
            return AjaxResult.error("找不到商户");
        }
        if (payerInfos.size() > 1) {
            return AjaxResult.error("找到多个商户");
        }

        log.info("updateOrder:" + channelOrder.toString());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&payAmount=").append(channelOrder.getPayAmount());
        stringBuilder.append("&orderStatus=").append(channelOrder.getOrderStatus());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(payerInfos.get(0).getApiKey());
        log.info("updateOrder:" + stringBuilder.toString());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }

        if (channelOrder.getAddSalesmanScore() != null && channelOrder.getAddSalesmanScore().equals("true")) {
            SalesmanScore salesmanScore = new SalesmanScore();
            salesmanScore.setOutScore(BigDecimal.ZERO);
            salesmanScore.setUserId(channelOrder.getChannelUserId());
            salesmanScore.setInScore(channelOrder.getPayAmount());
            salesmanScore.setCreateDate(new Date());
            salesmanScoreMapper.insertSalesmanScore(salesmanScore);
            return AjaxResult.success("success");
        }

        ChannelOrder searchOrder = new ChannelOrder();
        searchOrder.setPayerUserId(payerInfos.get(0).getPayerId());
        searchOrder.setPtOrderno(channelOrder.getChildOrderno());
        List<ChannelOrder> channelOrders = channelOrderService.selectChannelOrderList(searchOrder);
        if (channelOrders.size() == 0) {
            return AjaxResult.error("找不到订单号");
        }
        if (channelOrders.size() > 1) {
            return AjaxResult.error("找到两条相同的数据");
        }
        channelOrders.get(0).setPayAmount(channelOrder.getPayAmount());
        channelOrders.get(0).setOrderId(channelOrders.get(0).getPtOrderno());
        return payService.updateOrder(channelOrders.get(0));
    }

    /**
     * @param clientInfo
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PatchMapping("phoneOrder")
    @ResponseBody
    public AjaxResult updateOrderByPhone(ClientInfo clientInfo, String time) {
        // 手机端成功后更新数据
        return payService.updateOrderByPhone(clientInfo, time);
    }

    /**
     * @param clientInfo
     * @return
     */
    @ApiOperation("商家码通过订单列表")
    @PostMapping("phoneOrderList")
    @ResponseBody
    public AjaxResult updateOrderListByPhone(ClientInfo clientInfo, String time) {
        // 手机端成功后更新数据
        return payService.updateOrderByPhone(clientInfo, time);
    }

    /**
     * 钉钉收款回调
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("ddOrder")
    @ResponseBody
    public AjaxResult updateDDOrderByPhone(String data, String sign) {
        // 手机端成功后更新数据
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setData(data);
        clientInfo.setSign(sign);
        clientInfo.setChannelId("08");
        return payService.updateOrderByPhone(clientInfo, "");
    }

    /**
     * 云闪付收款回调
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("cloud")
    @ResponseBody
    public AjaxResult updateCloudOrderByPhone(String price, CloundCallMsg cloundCallMsg) {
        // 手机端成功后更新数据
        log.info("updateCloudOrderByPhone:" + cloundCallMsg.toString());
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(cloundCallMsg.getOutOrderNo());
        clientInfo.setRemark(cloundCallMsg.getTime());
        clientInfo.setAmount(cloundCallMsg.getPrice());
        clientInfo.setAccount(cloundCallMsg.getDeveice());
        clientInfo.setType(cloundCallMsg.getPayMode()); //  // 0固码 1正常
        clientInfo.setSign(cloundCallMsg.getSign());
        String time = cloundCallMsg.getTime();
        if (time != null) {
            log.info("新版本云闪付监听");
            Date date = new Date();
            date.setTime(Long.valueOf(time));
            clientInfo.setTime(date);
            long t = Long.valueOf(time) + 240 * 1000 - System.currentTimeMillis();
            if (t <= 0) {
                log.error("订单超时:" + cloundCallMsg.toString());
                return AjaxResult.error("订单超时");
            }
        }

        if (cloundCallMsg.getPayMode() != null && cloundCallMsg.getPayMode().equals("0")) {
            // 0固码
            clientInfo.setChannelId("17");
        } else {
            clientInfo.setChannelId("11");
        }

        return payService.updateOrderByPhone(clientInfo, price);
    }

    /**
     * 赞呗收款回调
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("zanbei")
    @ResponseBody
    public AjaxResult updateZanBeiOrderByPhone(String price, String sign, String time, String account, String orderId, String channel) {
        // 手机端成功后更新数据
        log.info("updateZanBeiOrderByPhone:" + price + ";" + sign + ";" + time + ";" + account + ";" + orderId);
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderId);
        clientInfo.setRemark(time);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(price)));
        clientInfo.setAccount(account);
        clientInfo.setSign(sign);
        Date date = new Date();
        date.setTime(Long.valueOf(time));
        clientInfo.setTime(date);
        long t = Long.valueOf(time) + 600 * 1000 - System.currentTimeMillis();
        if (t <= 0) {
            log.error("updateZanBeiOrderByPhone订单超时:");
            return AjaxResult.error("订单超时");
        }
        clientInfo.setChannelId(channel);
        return payService.updateOrderByPhone(clientInfo, price);
    }


    /**
     * 钉钉收款副号产码回调
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("ddQrcode")
    @ResponseBody
    public AjaxResult addDDQrcode(String mark, String money, String msg, String sign) {
        // 手机端成功后更新数据
        return channelCodeService.insertChannelCode(mark, money, msg, sign);
    }

    /**
     * 用来做测试的, 这个接口是用户已经通过支付宝扫码了,才能看到的页面
     *
     * @param orderId
     * @param mmap
     * @return
     */
    @ApiOperation("打开支付页面")
    @GetMapping("alipay")
    public String alipay(String orderId, String auth_code, ModelMap mmap, String opType) {
        //
//        AlipayClient alipayClient = new DefaultAlipayClient("https://openapi.alipay.com/gateway.do", "2019051064475084", payConfig.getAlipayPrivateKey(), "json", "UTF-8", payConfig.getAlipayPublicKey(), "RSA2");
//        AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
//        request.setCode(auth_code);
//        request.setGrantType("authorization_code");
//        String userId = "";
//        try {
//            AlipaySystemOauthTokenResponse oauthTokenResponse = alipayClient.execute(request);
//            // 付款方userid
//            userId = oauthTokenResponse.getUserId();
//        } catch (AlipayApiException e) {
//            //处理异常
//            e.printStackTrace();
//        }
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        System.out.println("alipay付款页面" + channelOrder.toString());
        if (channelOrder.getPayUrl() != null) {
            try {
                mmap.put("payUrl", URLEncoder.encode(channelOrder.getPayUrl(), "utf-8"));
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        mmap.put("channelOrder", channelOrder);
        if (channelOrder.getSuccessTime() != null) {
            mmap.put("qrcode", "订单已成功");
            return "openOutTime";
        } else if (channelOrder.getStatus().equals("1")) {
            mmap.put("qrcode", "订单已超时");
            return "openOutTime";
        }
        if (channelOrder.getAccount() == null) {
            mmap.put("qrcode", "找不到支付账号");
            return "alipay/error";
        }
//        if (channelOrder.getAccount() == null) {
//            // 未分配账号
//            // 打开支付页面后再轮询账号
//            ChannelAccount searchAcc = new ChannelAccount();
//            searchAcc.setStatus("0");
//            searchAcc.setChannelUserId(channelOrder.getChannelUserId());
//            List<ChannelAccount> channelAccounts = channelAccountService.selectChannelAccountList(searchAcc);
//            Random ra = new Random();
//            ChannelAccount account = channelAccounts.get(ra.nextInt(channelAccounts.size()));
//            channelOrder.setAccount(account.getAccount());
//        }
//        channelOrder.setFromAlipayId("1");
        channelOrderService.updateChannelOrder(channelOrder);
        mmap.put("account", channelOrder.getAccount());
        mmap.put("expiredTime", payService.getExpiredTime(channelOrder.getCreateTime()));
        String type = "alipay";
        if (channelOrder.getPayType().equals("01")) {
            // 红包
            type = "alipay/redpay";
        } else if (channelOrder.getPayType().equals("03")) {
            // 转账
            type = "alipay/newredpay";
        } else if (channelOrder.getPayType().equals("02")) {
            // 转账
            type = "alipay/costs";
        } else if (channelOrder.getPayType().equals("04")) {
            // 转账
            long time = channelOrder.getCreateTime().getTime() + 300 * 1000 - System.currentTimeMillis();
            mmap.put("time", time);
            if (time <= 0) {
                mmap.put("qrcode", "订单已超时");
                return "openOutTime";
            }
            type = "alipay/newBank3";
        } else if (channelOrder.getPayType().equals("05")) {
            // 企业号转账
            type = "alipay/enterprise";
        } else if (channelOrder.getPayType().equals("07")) {
            // 链接红包
            type = "alipay/linkredpay2";
        } else if (channelOrder.getPayType().equals("08") && "download".equals(opType)) {
            // 钉钉
            type = "alipay/downDD";
        } else if (channelOrder.getPayType().equals("08")) {
            // 钉钉
            type = "alipay/linkdd";
        }
        return type;
    }

    @ApiOperation("获取列表")
    @PostMapping("list")
    @ResponseBody
    public AjaxResult channelList(@RequestBody ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(channelOrder.getBusinessId());
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        log.info("channelList:" + stringBuilder.toString());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);
        List<JSONObject> results = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("childOrderno", list.get(0).getChildOrderno());
            jsonObject.put("payAmount", list.get(0).getPayAmount());
            jsonObject.put("orderStatus", list.get(0).getOrderStatus());
            results.add(jsonObject);
        }
        return AjaxResult.success("success", results);
    }

    @ApiOperation("获取列表")
    @PostMapping("list/form")
    @ResponseBody
    public AjaxResult channelListByForm(ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(channelOrder.getBusinessId());
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        log.info("channelList:" + stringBuilder.toString());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);
        List<JSONObject> results = new ArrayList<>();
        for (int i = 0; i < list.size(); i++) {
            JSONObject jsonObject = new JSONObject();
            jsonObject.put("childOrderno", list.get(0).getChildOrderno());
            jsonObject.put("payAmount", list.get(0).getPayAmount());
            jsonObject.put("orderStatus", list.get(0).getOrderStatus());
            results.add(jsonObject);
        }
        return AjaxResult.success("success", results);
    }

    @ApiOperation("获取订单状态")
    @GetMapping("orderStatus/{orderId}")
    @ResponseBody
    public AjaxResult getOrderStatus(@PathVariable("orderId") String orderId) {
        ChannelOrder channelOrder = channelOrderService.selectChannelOrderById(orderId);
        return AjaxResult.success("操作成功", channelOrder);
    }

    @ApiOperation("获取当个数据")
    @PostMapping("singleOrder")
    @ResponseBody
    public AjaxResult sigleOrder(@RequestBody ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(channelOrder.getBusinessId());
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        log.info("channelList:" + stringBuilder.toString());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);
        ChannelOrder result = new ChannelOrder();
        if (list.size() > 1) {
            return AjaxResult.error("找到多条记录");
        }
        if (list.size() == 0) {
            return AjaxResult.error("找不到数据");
        }

        JSONObject jsonObject = new JSONObject();
        jsonObject.put("childOrderno", list.get(0).getChildOrderno());
        jsonObject.put("payAmount", list.get(0).getPayAmount());
        String status = "0";
        if (list.get(0).getOrderStatus().equals("1") || list.get(0).getOrderStatus().equals("2") || list.get(0).getOrderStatus().equals("3")) {
            status = "1";
        }
        jsonObject.put("orderStatus", status);
        log.info("查询单个：" + jsonObject.toJSONString());
        return AjaxResult.success("success", jsonObject);
    }

    @ApiOperation("获取当个数据")
    @PostMapping("singleOrder/form")
    @ResponseBody
    public AjaxResult sigleFormOrder(ChannelOrder channelOrder) {
        BusinessInfo businessInfo = businessInfoService.selectBusinessInfoById(channelOrder.getBusinessId());
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("businessId=").append(channelOrder.getBusinessId());
        stringBuilder.append("&childOrderno=").append(channelOrder.getChildOrderno());
        stringBuilder.append("&time=").append(channelOrder.getTime());
        stringBuilder.append("&").append(businessInfo.getApiKey());
        log.info("channelList:" + stringBuilder.toString());
        boolean b = Md5Utils.vertifyAndroidMD5(stringBuilder.toString(), channelOrder.getSign());
        if (b == false) {
            // 如果校验失败要告警 TODO:
            return AjaxResult.error("鉴权失败");
        }
        List<ChannelOrder> list = channelOrderService.selectChannelOrderList(channelOrder);
        ChannelOrder result = new ChannelOrder();
        if (list.size() > 1) {
            return AjaxResult.error("找到多条记录");
        }
        if (list.size() == 0) {
            return AjaxResult.error("找不到数据");
        }
        String status = "0";
        if (list.get(0).getOrderStatus().equals("1") || list.get(0).getOrderStatus().equals("2") || list.get(0).getOrderStatus().equals("3")) {
            status = "1";
        }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("childOrderno", list.get(0).getChildOrderno());
        jsonObject.put("payAmount", list.get(0).getPayAmount());
        jsonObject.put("orderStatus", status);
        log.info("查询单个form：" + jsonObject.toJSONString());
        return AjaxResult.success("success", jsonObject);
    }

    @GetMapping("test")
    public String test(String account, String payType, ModelMap mmap) {
        if (account == null) {
            mmap.put("account", "");
            mmap.put("payType", "");
        } else {
            mmap.put("account", account);
            mmap.put("payType", payType);
        }
        return "test1";
    }

    @GetMapping("bank")
    public String bank() {
        return "alipay/bank1";
    }

    @GetMapping("third/{orderId}")
    public String third(@PathVariable("orderId") String orderId, ModelMap mmap) {
        String url = payConfig.getCaiNiaoHost() + "/pay/alipay?orderId=" + orderId;
        mmap.put("url", url);
        return "alipay/third";
    }

    /**
     * 农信易扫
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("nxys")
    @ResponseBody
    public AjaxResult updateNXYSOrderByPhone(NxysCallMsg nxysCallMsg, BigDecimal money) {
        // 手机端成功后更新数据
        log.info("updateNXYSOrderByPhone:" + nxysCallMsg.toString());
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(nxysCallMsg.getOrderNo());
        clientInfo.setAmount(money);
        clientInfo.setAccount(nxysCallMsg.getUid());
        clientInfo.setSign(nxysCallMsg.getSign());
        clientInfo.setDeviceNum(nxysCallMsg.getOrderTime());
        clientInfo.setChannelId("12");
        return payService.updateOrderByPhone(clientInfo, nxysCallMsg.getMoney());
    }

    /**
     * 中原聚商
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("zy")
    @ResponseBody
    public AjaxResult updateZYOrderByPhone(String content, String sign, String time) {
        // 手机端成功后更新数据
        try {
            String str = URLDecoder.decode(content, "utf-8");
            log.info("updateZYOrderByPhone:" + content);
            JSONObject jsonObject = JSONObject.parseObject(str);
            String userName = jsonObject.getString("username");
            if (userName == null || "".equals(userName.trim())) {
                return AjaxResult.error("非法用户");
            }
            String data = jsonObject.getString("data");
            JSONObject message = JSONObject.parseObject(data);
            String title = message.getString("title");
            String s = message.getString("content");
            if (!s.startsWith("云闪付收款") && !"聚商".equals(title) && !"支付宝通知".equals(title) && !"微信支付".equals(title) && !"微信收款商业版".equals(title)) {
                return AjaxResult.error("非法类型");
            }
            String amount = "0";
            String channelId = "13";

            if ("聚商".equals(title)) {
                channelId = "13";
                String[] ss1 = s.split("收款");
                if (ss1.length < 2) {
                    return AjaxResult.error("解析出错");
                }
                amount = ss1[1].replace("元", "");
            } else if ("微信支付".equals(title)) {
                // [2条]微信支付: 微信支付收款0.10元(朋友到店)
                channelId = "15_1";
                String[] ss1 = s.split("微信支付收款");
                if (ss1.length < 2) {
                    return AjaxResult.error("解析出错");
                }
                amount = ss1[1].split("元")[0];
            } else if ("微信收款商业版".equals(title)) {
                // 收款0.02元（老客到店）
                channelId = "16";
                String[] ss1 = s.replace("微信收款商业版: ", "").split("收款");
                if (ss1.length < 2) {
                    return AjaxResult.error("解析出错");
                }
                amount = ss1[1].split("元")[0];
            } else if (s.startsWith("云闪付收款")) {
                // {"content":"云闪付收款1.10元。","packagename":"io.va.exposed","title":"消息推送"}
                channelId = "17";
                amount = s.replace("云闪付收款", "").replace("元。", "").trim();
            } else if ("支付宝通知".equals(title)) {
                channelId = "09";
                String[] ss1 = s.split("通过扫码向你付款");
                if (ss1.length > 2) {
                    return AjaxResult.error("不要撸单,谢谢");
                }
                if (ss1.length > 1) {
                    // 支付宝通知 无语通过扫码向你付款0.02元
                    amount = ss1[1].replace("元", "");
                } else {
                    // 成功收款0.01元。享免费...,点击查看
                    ss1 = s.split("。");
                    String[] ss2 = ss1[0].split("成功收款");
                    amount = ss2[1].replace("元", "");
                    if (ss2.length < 2) {
                        return AjaxResult.error("解析支付宝出错");
                    }
                }
            }

            ClientInfo clientInfo = new ClientInfo();
            clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(amount)));
            clientInfo.setAccount(userName);
            clientInfo.setSign(sign);
            clientInfo.setChannelId(channelId);
            return payService.updateOrderByPhone(clientInfo, time);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("");
    }

    /**
     * 中原聚商
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("zy2")
    @ResponseBody
    public AjaxResult updateZY2OrderByPhone(@RequestBody ZYCallMsg zyCallMsg) {
        // 手机端成功后更新数据
        log.info("updateZYOrderByPhone:" + zyCallMsg.toString());
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(zyCallMsg.getAmount())));
        clientInfo.setAccount(zyCallMsg.getPhoneNo());
        clientInfo.setSign(zyCallMsg.getSign());
        clientInfo.setChannelId("13");
        return payService.updateOrderByPhone(clientInfo, zyCallMsg.getAmount());
    }

    /**
     * 中原聚商
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("wx")
    @ResponseBody
    public AjaxResult updatWXOrderByPhone(String weixinAccount, String sign, String money, String timeStr, String time) {
        // 手机端成功后更新数据
        try {
            String _weixinAccount = URLDecoder.decode(weixinAccount, "utf-8");
            String _timeStr = URLDecoder.decode(timeStr, "utf-8");
            ClientInfo clientInfo = new ClientInfo();
            clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
            clientInfo.setAccount(_weixinAccount);
            clientInfo.setSign(sign);
            clientInfo.setType(_timeStr);
            clientInfo.setDeviceNum(time);
            clientInfo.setChannelId("15");
            return payService.updateOrderByPhone(clientInfo, money);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return AjaxResult.error("");
    }


    /**
     * 微信
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("wx2")
    @ResponseBody
    public AjaxResult updatWX2OrderByPhone(String from_wxid, String type, String from_name, String final_from_wxid, String final_from_name, String robwxid, String msg, String time) {
        // 手机端成功后更新数据
        if (!"600".equals(type)) {
            return AjaxResult.error("非收款类型");
        }
        JSONObject jsonObject = JSONObject.parseObject(msg);
        String money = jsonObject.getString("money");
        String shopowner = jsonObject.getString("shopowner");
        String[] owners = shopowner.split("[(]");
        String _weixinAccount = owners[0];
        System.out.println(from_wxid + ";" + type + ";" + from_name + ";" + final_from_wxid + ";" + final_from_wxid + ";" + final_from_name + ";" + robwxid + ";" + msg + ";" + time);
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setAccount(_weixinAccount);
        clientInfo.setChannelId("15");
        return payService.updateOrderByPhone(clientInfo, "___");
    }

    /**
     * 微信3
     *
     * @param type 当前订单类型 :WXPAY(个码)  PHONEPAY(手机号转账) DIANYUAN(店员通)
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("wx3")
    @ResponseBody
    public String updatWX3OrderByPhone(String type, String money, String no, String time, String mark, String sign) {
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setSign(sign);
        clientInfo.setType(type);
        if (Long.valueOf(time) + 360 * 1000 - System.currentTimeMillis() < 0) {
            // 如果超过6分钟才回调 不予处理
            return "订单超时";
        }
        clientInfo.setDeviceNum(time);
        if (type.equals("DIANYUAN")) {
            clientInfo.setChannelId("15");
            clientInfo.setAccount(mark);// 回调账号
            clientInfo.setFromName(no); // 设备账号
        } else if (type.equals("PHONEPAY")) {
            clientInfo.setChannelId("19");
            clientInfo.setAccount(no);
        } else {
            return "个码暂时不支持";
        }
        AjaxResult result = payService.updateOrderByPhone(clientInfo, money);
        if ((result.get("code") + "").equals("0")) {
            return "success";
        }
        return result.get("msg") + "";
    }

    @PostMapping("redPackage")
    @ResponseBody
    public AjaxResult updatRedPackage(String memo, String orderId) {
        ChannelOrder order = new ChannelOrder();
        order.setSubmitUrl(memo);
        order.setOrderId(orderId);
        channelOrderService.updateRedPackage(order);
        return success("保存成功,请耐心等候");
    }

    /**
     * 农信易扫
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("qiye")
    @ResponseBody
    public AjaxResult updateQiyeOrderByPhone(String userId, String mark, String orderNo, String no, String time, String sign, String money) {
        // 时间超时不予处理
        if (null != time && !"".equals(time) && !"null".equals(time)) {
            log.info("updateQiyeOrderByPhone====>userId:" + userId + ";mark:" + mark + ";orderNo:" + orderNo + ";no:" + no + ";time:" + time + ";sign:" + sign + ";money:" + money);
            long time1 = Long.valueOf(time) + 240 * 1000 - System.currentTimeMillis();
            if (time1 <= 0) {
                return AjaxResult.error("订单超时");
            }
        }
        // 手机端成功后更新数据
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderNo);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setAccount(no);
        clientInfo.setFromUid(userId);
        clientInfo.setSign(sign);
        clientInfo.setRemark(mark);
        clientInfo.setDeviceNum(time);
        log.info("updateQiyeOrderByPhone,mark:" + mark + ";amount:" + money);
        if ("转账".equals(mark) || "收款".equals(mark)) {
            clientInfo.setChannelId("26"); // 注意：新模式转账和固码和在一起 设置为 09
        } else {
            clientInfo.setChannelId("25");
        }
        log.info("updateQiyeOrderByPhone:" + clientInfo.toString());
        return payService.updateOrderByPhone(clientInfo, money);
    }

    /**
     * 农信易扫
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("guma")
    @ResponseBody
    public AjaxResult updateQiye2OrderByPhone(String userId, String mark, String orderNo, String no, String time, String sign, String money) {
        // 手机端成功后更新数据
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderNo);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setAccount(no);
        clientInfo.setFromUid(userId);
        clientInfo.setSign(sign);
        clientInfo.setRemark(mark);
        clientInfo.setDeviceNum(time);
        log.info("updateQiye2OrderByPhone,mark:" + mark + ";amount:" + money);
        clientInfo.setChannelId("_09"); // 注意：新模式转账和固码和在一起 设置为 09
        log.info("updateQiyeOrderByPhone:" + clientInfo.toString());
        return payService.updateOrderByPhone(clientInfo, money);
    }

    /**
     * 农信易扫
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("shenghuo")
    @ResponseBody
    public AjaxResult updateShenghuohaoOrderByPhone(String userId, String mark, String orderNo, String no, String time, String sign, String money) {
        // 手机端成功后更新数据
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderNo);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setAccount(no);
        clientInfo.setFromUid(userId);
        clientInfo.setSign(sign);
        clientInfo.setRemark(mark);
        clientInfo.setDeviceNum(time);
        clientInfo.setChannelId("31");
        log.info("updateQiyeOrderByPhone,mark:" + mark + ";amount:" + money);
        return payService.updateOrderByPhone(clientInfo, money);
    }

    /**
     * 智享收款回调
     *
     * @param
     * @return
     */
    @ApiOperation("手机收到付款后,通知更新订单")
    @PostMapping("zhixiang")
    @ResponseBody
    public AjaxResult updateZhiXiangOrderByPhone(String price, String sign, String time, String account, String orderId) {
        // 手机端成功后更新数据
        log.info("updateZhiXiangOrderByPhone:" + price + ";" + sign + ";" + time + ";" + account + ";" + orderId);
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderId);
        clientInfo.setRemark(time);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(price)));
        clientInfo.setAccount(account);
        clientInfo.setSign(sign);
        Date date = new Date();
        date.setTime(Long.valueOf(time));
        clientInfo.setTime(date);
        clientInfo.setChannelId("27");
        return payService.updateOrderByPhone(clientInfo, price);
    }

    /**
     * 淘宝现金红包
     *
     * @param
     * @return
     */
    @ApiOperation("旺信产码")
    @PostMapping("wangxincode")
    @ResponseBody
    public AjaxResult insertWangxinCode(String no, String dt, String sign, String qrList) {
        // 手机端成功后更新数据
        log.info("insertWangxinCode NO:" + no + ";dt:" + dt + ";sign:" + sign + ";qrList" + qrList + ";");
        return channelCodeService.insertChannelCodes(no, qrList, dt, sign);
    }

    /**
     * 淘宝现金红包
     *
     * @param
     * @return
     */
    @ApiOperation("旺信产码")
    @PostMapping("wangxin")
    @ResponseBody
    public AjaxResult updateWangxinCode(String no, String dt, String sign, String type, String orderNo, String money) {
        // 手机端成功后更新数据
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderNo);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setAccount(no);
        clientInfo.setSign(sign);
        clientInfo.setRemark(type);
        clientInfo.setDeviceNum(dt);
        clientInfo.setChannelId("28");
        log.info("updateWangxinCode:" + clientInfo.toString());
        return payService.updateOrderByPhone(clientInfo, money);
    }

    /**
     * 淘宝现金红包
     *
     * @param
     * @return
     */
    @ApiOperation("零花钱产码")
    @PostMapping("linghuaqian")
    @ResponseBody
    public AjaxResult updateLinghuaqian(String no, String time, String sign, String mark, String orderNo, String money) {
        // 手机端成功后更新数据
        ClientInfo clientInfo = new ClientInfo();
        clientInfo.setOrderId(orderNo);
        clientInfo.setAmount(BigDecimal.valueOf(Double.valueOf(money)));
        clientInfo.setAccount(no);
        clientInfo.setSign(sign);
        clientInfo.setRemark(mark);
        clientInfo.setDeviceNum(time);
        clientInfo.setChannelId("29");
        log.info("updatelinghuaqian:" + clientInfo.toString());
        return payService.updateOrderByPhone(clientInfo, money);
    }

    /**
     * 验证opc账号
     *
     * @param
     * @return
     */
    @ApiOperation("验证opc账号")
    @PostMapping("validPhones")
    @ResponseBody
    public AjaxResult validPhones(@RequestBody String phones) {
        // 手机端成功后更新数据
        return payService.validPhones(phones);
    }

    /**
     * 验证opc账号
     *
     * @param
     * @return
     */
    @ApiOperation("成功通知")
    @PostMapping("opcSuccess")
    @ResponseBody
    public AjaxResult opcSuccess(@RequestBody Opc phone) {
        // 手机端成功后更新数据
        return payService.opcSuccess(phone.getPhone());
    }

    @PostMapping("addGoods")
    @ResponseBody
    public AjaxResult addGoods(@RequestBody List<HashMap<String, String>> goods) {
        for (HashMap<String, String> good : goods) {
            if (good.get("image") == null || good.get("price") == null) {
                continue;
            }
            GoodsInfo goodsInfo = new GoodsInfo();
            goodsInfo.setImgUrl(good.get("image"));
            try {
                goodsInfo.setPrice(new BigDecimal(good.get("price")));
            } catch (Exception e) {
                continue;
            }
            goodsInfo.setProductName(good.get("description"));
            GoodsInfo search = new GoodsInfo();
            search.setProductName(goodsInfo.getProductName());
            List<GoodsInfo> goodsInfos = goodsInfoService.selectGoodsInfoList(search);
            if (!goodsInfos.isEmpty()) {
                continue;
            }
            goodsInfo.setCreateTime(new Date());
            goodsInfo.setUpdateTime(new Date());
            goodsInfoService.insertGoodsInfo(goodsInfo);
        }
        return AjaxResult.success("success");
    }
}


